import sys
import crawler
import db
import re
import time
import threading

def showPages(start=-1, count=-1):
	crawler.Crawler.dbLock.acquire()
	DBHelper = db.DBOps()
	DBHelper.connDB()
	pages = DBHelper.getPages(start, count)
	for page in pages:
		print page[0]
	print "Total Page Count: {}".format(DBHelper.getPageCount())
	DBHelper.closeDB()
	crawler.Crawler.dbLock.release()

if __name__ == "__main__":
	Crawler = None
	if len(sys.argv) > 1:
		if sys.argv[1].lower == "help":
			print "usage: {} [command]".format(sys.argv[0])
			print "commands are:\n\tupdate - updates all pages in db\n\tshow [start [count]] - shows 'count' pages starting from 'start'\n\tseed link - crawls link"
			print "\thelp - displays that menu"
			exit(0)
		elif sys.argv[1].lower() == "show":
			try:
				start = -1
				count = -1
				if len(sys.argv) >= 4:
					start, count = int(sys.argv[2]), int(sys.argv[3])
				elif len(sys.argv) >= 3:
					start = int(sys.argv[2])
				showPages(start, count)
				exit(0)
			except Exception as e:
				print e
				print "start and count must be integers"
				print "usage: {} {} [start [count]]".format(sys.argv[0], sys.argv[1])
				exit(1)
		elif sys.argv[1].lower() == "seed":
			if len(sys.argv) < 3:
				print "seed command takes 1 parameters!"
				print "usage: {} {} link".format(sys.argv[0], sys.argv[1])
				exit(1)
			seed = sys.argv[2]
			if not re.match("(.*?)://(.*?)", seed):
				print "link is not valid it should be in format: http://domainname/"
				exit(1)
			if not seed.endswith('/'):
				seed = seed + '/'
			Crawler = crawler.Crawler(seed)
			Crawler.daemon = True
			Crawler.start()
		elif sys.argv[1].lower() == "update":
			print "Not implemented yet!"
			exit(0)
		else:
			print "usage: {} [command]".format(sys.argv[0])
			print "commands are:\n\tupdate - updates all pages in db\n\tshow [start [count]] - shows 'count' pages starting from 'start'\n\tseed link - crawls link"
			print "\thelp - displays that menu"
			exit(1)
		
	while True:
		line = raw_input(":> ")
		if line.lower() == "status":
			if Crawler:
				print Crawler.getStatus()
			else:
				print "Crawler not started"
		elif line.lower() == "exit":
			if Crawler:
				Crawler.stop()
				print "Closing threads please wait.."
				time.sleep(10)
				print "Good Bye!"
				crawler.Crawler.dbLock = threading.Lock()
				Crawler = None
			break
		elif line.lower().startswith("show"):
			start = -1
			count = -1
			for param in line.split(' '):
				if not param:
					continue
				if param.lower() == "show":
					continue
				if start == -1:
					start = int(param)
					continue
				count = int(param)
			showPages(start, count)
		elif line.lower() == "help":
			print "usage: {} [command]".format(sys.argv[0])
			print "commands are:\n\tupdate - updates whole pages in db\n\tshow [start [count]] - shows 'count' pages starting from 'start'\n\tseed link - crawls link"
			print "\thelp - displays that menu\n\tclear - clears pages table\n\tstop - stops crawler\n\texit - closes executer"
		elif line.lower().startswith("seed"):
			if Crawler:
				if Crawler.done():
					Crawler = None
				else:
					print "Crawler already started!"
					continue
			lineSplit = line.split(' ')
			if len(lineSplit) < 2:
				print "seed command takes 1 parameters!"
				print "usage: seed link"
				continue
			seed = lineSplit[1]
			if not re.match("(.*?)://(.*?)", seed):
				print "link is not valid it should be in format: http://domainname/"
				continue
			if not seed.endswith('/'):
				seed = seed + '/'
			Crawler = crawler.Crawler(seed)
			Crawler.daemon = True
			crawler.Crawler.dbLock = threading.Lock()
			Crawler.start()
		elif line.lower() == "stop":
			if Crawler:
				Crawler.stop()
				print "Closing threads please wait.."
				time.sleep(10)
				print "Crawler stopped!"
				Crawler = None
				crawler.Crawler.dbLock = threading.Lock()
		elif line.lower() == "clear":
			crawler.Crawler.dbLock.acquire()
			DBHelper = db.DBOps()
			DBHelper.connDB()
			DBHelper.dropTable()
			DBHelper.closeDB()
			crawler.Crawler.dbLock.release()
			print "Table dropped succesfully!"
		else:
			print "Unknown command :("
	exit(0)

exit(0)

